<template>
  <div class="discover page-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar title="发现活动" fixed placeholder />

    <!-- 分类标签栏 -->
    <div class="content-container">
      <van-tabs v-model:active="activeCategory" swipeable animated  class="custom-tabs">
        <template #nav-right>
          <div class="nav-right-placeholder"></div>
        </template>
        <van-tab v-for="category in categories" :key="category.id" :title="category.name">
          <!-- 列表布局 -->
          <div class="activity-list-container">
            <div class="activity-list">
              <activity-list-item v-for="activity in filteredActivities" :key="activity.id" :activity="activity"
                @click="goToDetail(activity.id)" />

              <!-- 加载更多 -->
              <div class="load-more" v-if="hasMore" @click="loadMore">
                <van-loading v-if="loading" size="24px" color="#4080ff">加载中...</van-loading>
                <span v-else>加载更多</span>
              </div>

              <!-- 防御性检查 -->
              <van-empty v-if="filteredActivities.length === 0 && !loading" description="暂无活动" />
            </div>
          </div>
        </van-tab>
      </van-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import ActivityListItem from '@/components/activity/ActivityListItem.vue';
import { useActivityStore } from '@/stores/activity';
import { showToast } from 'vant';
import { getImageUrl } from '@/utils/image';

const router = useRouter();
const activityStore = useActivityStore();
const activeCategory = ref(0);
const loading = ref(false);
const hasMore = ref(true);
const currentPage = ref(1);
const pageSize = ref(10);

// 活动分类
const categories = ref([
  { id: 0, name: '全部' },
  { id: 1, name: '休闲骑行' },
  { id: 2, name: '山地骑行' },
  { id: 3, name: '公路骑行' },
  { id: 4, name: '夜骑' },
  { id: 5, name: '亲子骑行' },
  { id: 6, name: '环湖骑行' },
  { id: 7, name: '长途骑行' }
]);

// 活动数据
const activities = ref([]);

// 添加模拟数据
const addMockData = () => {
  const mockActivities = [
    {
      id: 'mock-1',
      title: '周末休闲骑行活动',
      description: '周末一起来骑行吧，沿着湖边慢慢骑，欣赏美丽风景，放松心情。适合初学者参加，全程约30公里。',
      location: '西湖边骑行道',
      startTime: '2023-12-16 09:00:00',
      cover: 'https://img01.yzcdn.cn/vant/cat.jpeg',
      tags: ['休闲骑行', '周末活动']
    },
    {
      id: 'mock-2',
      title: '城市夜骑体验',
      description: '夜晚的城市别有一番风味，一起来体验夜骑的乐趣吧。全程有专业领队带队，确保安全。',
      location: '市中心广场集合',
      startTime: '2023-12-15 19:30:00',
      cover: 'https://img01.yzcdn.cn/vant/apple-1.jpg',
      tags: ['夜骑', '城市探索']
    },
    {
      id: 'mock-3',
      title: '山地车挑战赛',
      description: '专业山地车赛道，挑战自我极限。适合有一定骑行经验的车友，全程设有补给站。',
      location: '青龙山自行车公园',
      startTime: '2023-12-20 08:00:00',
      cover: 'https://img01.yzcdn.cn/vant/apple-2.jpg',
      tags: ['山地骑行', '挑战赛']
    },
    {
      id: 'mock-4',
      title: '亲子骑行欢乐日',
      description: '带上孩子一起来骑行，体验亲子时光。路线平缓，设有多个互动游戏点，让孩子在骑行中学习和成长。',
      location: '城市公园',
      startTime: '2023-12-17 10:00:00',
      cover: 'https://img01.yzcdn.cn/vant/apple-3.jpg',
      tags: ['亲子骑行', '家庭活动']
    },
    {
      id: 'mock-5',
      title: '环湖百公里挑战',
      description: '环绕整个湖泊骑行，欣赏湖光山色。全程约100公里，适合有长途骑行经验的车友。',
      location: '东湖骑行公园',
      startTime: '2023-12-23 07:00:00',
      cover: 'https://img01.yzcdn.cn/vant/apple-4.jpg',
      tags: ['环湖骑行', '长途骑行']
    },
    {
      id: 'mock-6',
      title: '公路骑行训练营',
      description: '专业公路车训练，提升骑行技巧和耐力。由资深教练指导，适合想提升骑行水平的车友。',
      location: '郊外公路训练基地',
      startTime: '2023-12-18 08:30:00',
      cover: 'https://img01.yzcdn.cn/vant/cat.jpeg',
      tags: ['公路骑行', '训练营']
    },
    {
      id: 'mock-7',
      title: '城郊探秘骑行',
      description: '探索城市周边的自然风光和人文景观，发现不一样的美景。中等难度，全程约50公里。',
      location: '城市东郊集合点',
      startTime: '2023-12-24 09:00:00',
      cover: 'https://img01.yzcdn.cn/vant/apple-1.jpg',
      tags: ['休闲骑行', '探秘']
    },
    {
      id: 'mock-8',
      title: '骑行技巧交流会',
      description: '资深车友分享骑行技巧和经验，包括装备选择、姿势调整、爬坡技巧等。室内活动，轻松参与。',
      location: '自行车俱乐部',
      startTime: '2023-12-14 19:00:00',
      cover: 'https://img01.yzcdn.cn/vant/apple-2.jpg',
      tags: ['技巧交流', '室内活动']
    }
  ];

  return mockActivities;
};

// 根据分类筛选活动
const filteredActivities = computed(() => {
  // 如果没有真实数据，添加模拟数据
  if (activities.value.length === 0) {
    activities.value = addMockData();
  }

  if (activeCategory.value === 0) {
    return activities.value;
  } else {
    const categoryName = categories.value[activeCategory.value].name;
    return activities.value.filter(activity =>
      activity.tags && activity.tags.some(tag => tag.includes(categoryName))
    );
  }
});

// 获取活动列表
const fetchActivities = async () => {
  if (loading.value) return;

  loading.value = true;

  try {
    // 尝试从API获取数据
    const response = await activityStore.getActivityList({
      page: currentPage.value,
      pageSize: pageSize.value,
      category: activeCategory.value === 0 ? '' : categories.value[activeCategory.value].name
    });

    // 处理返回的数据
    const newActivities = response.list.map(item => ({
      id: item.id,
      title: item.title,
      description: item.content || item.description,
      location: item.location,
      startTime: item.startTime || item.start_time,
      cover: getImageUrl(item.cover),
      tags: item.tags || [categories.value[activeCategory.value].name]
    }));

    if (currentPage.value === 1) {
      // 如果API返回的数据为空，使用模拟数据
      activities.value = newActivities.length > 0 ? newActivities : addMockData();
    } else {
      activities.value = [...activities.value, ...newActivities];
    }

    // 判断是否还有更多数据
    hasMore.value = newActivities.length >= pageSize.value;
  } catch (error) {
    console.error('获取活动列表失败:', error);
    showToast('使用模拟数据展示');
    // 发生错误时使用模拟数据
    activities.value = addMockData();
    hasMore.value = false;
  } finally {
    loading.value = false;
  }
};

// 加载更多活动
const loadMore = async () => {
  if (loading.value || !hasMore.value) return;

  currentPage.value += 1;
  await fetchActivities();
};

// 切换分类时重置数据
const resetData = () => {
  activities.value = [];
  currentPage.value = 1;
  hasMore.value = true;
  fetchActivities();
};

// 监听分类变化
watch(activeCategory, () => {
  resetData();
});

// 跳转到活动详情
const goToDetail = (id) => {
  router.push(`/activity/detail/${id}`);
};

onMounted(() => {
  // 初始加载活动数据
  fetchActivities();
});
</script>

<style lang="scss" scoped>
.discover {
  background-color: #f7f8fa;
  height: 100%;
  padding-bottom: 10px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

:deep(.van-nav-bar) {
  background-color: #fff;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.05);

  .van-nav-bar__title {
    font-size: 18px;
    font-weight: 500;
    color: #333;
  }
}

.content-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .custom-tabs {
    flex: 1;
    display: flex;
    flex-direction: column;

 

    :deep(.van-tabs__content) {
      flex: 1;
      overflow: hidden;
      position: relative;
    }

    :deep(.van-tab__pane) {
      height: 100%;
      overflow: hidden;
    }

    :deep(.van-tabs__nav) {
      padding: 6px 8px;
      background-color: #fff;
    }

    :deep(.van-tab) {
      padding: 0 14px;
      font-size: 14px;
      color: #666;
      line-height: 32px;
      height: 32px;
      background-color: #f5f7fa;
      border-radius: 16px;
      margin: 0 4px;
      transition: all 0.2s ease;
    }

    :deep(.van-tab--active) {
      color: #fff;
      font-weight: 500;
      background-color: #4080ff;
    }

    :deep(.van-tabs__line) {
      display: none;
    }
  }
}

.activity-list-container {
  height: calc(100vh - 80px); /* 减去导航栏和标签栏的高度 */
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  padding-bottom: 90px;
  
  /* 修改滚动条样式 */
  scrollbar-width: thin;
  -ms-overflow-style: -ms-autohiding-scrollbar;
  
  &::-webkit-scrollbar {
    width: 4px;
  }
  
  &::-webkit-scrollbar-track {
    background: transparent;
  }
  
  &::-webkit-scrollbar-thumb {
    background-color: rgba(0, 0, 0, 0.2);
    border-radius: 4px;
  }
}

.activity-list {
  padding: 16px 12px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.load-more {
  text-align: center;
  color: #4080ff;
  padding: 16px 0 24px;
  font-size: 14px;

  &:active {
    opacity: 0.8;
  }
}

.loading-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}
</style>
